package hy;


import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.framework.recipes.locks.InterProcessReadWriteLock;
import org.apache.curator.retry.RetryUntilElapsed;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class CuratorLock {
    String url="192.168.184.100:2181";
    CuratorFramework client;

    @Before
    public void init(){
        //超时后重连，每三秒就重新尝试连接，如果共用时超过了10秒就结束重连
        RetryPolicy r=new RetryUntilElapsed(10000,3000);
        client= CuratorFrameworkFactory.builder().
                connectString(url).
                //客户端与zk连接成功后，zk出现故障就会重连，如果超过1秒还连接不上
                sessionTimeoutMs(1000).
                retryPolicy(r).build();
        client.start();
    }

    @After
    public void close(){
        client.close();
    }

    @Test//排它锁
    public void mutex()throws Exception{
        InterProcessLock lock=new InterProcessMutex(client,"/locks");
        System.out.println("等待获取锁对象");
        //获取锁
        lock.acquire();
        for(int i=0;i<10;i++){
            Thread.sleep(3000);
            System.out.println(i);
        }
        //释       lock.release();
        System.out.println("成功释放锁！");
    }

    @Test//可并发读，但读锁获取后，不能再申请写锁
    public void readLock()throws Exception{
        InterProcessReadWriteLock ipr=new InterProcessReadWriteLock(client,"/locks");
        System.out.println("等待获取锁...");
        InterProcessLock lock=ipr.readLock();
        lock.acquire();
        for(int i=0;i<10;i++){
            Thread.sleep(3000);
            System.out.println(i);
        }
        lock.release();
        System.out.println("成功释放锁!");
    }

    @Test
    public void writeLock()throws Exception{
        InterProcessReadWriteLock ipr=new InterProcessReadWriteLock(client,"/locks");
        System.out.println("等待获取锁对象....");
        InterProcessLock lock=ipr.writeLock();
        lock.acquire();
        for(int i=0;i<10;i++){
            Thread.sleep(3000);
            System.out.println(i);
        }
        lock.release();
        System.out.println("成功释放锁!");
    }


}
